package cron.core.loader;


import cn.hutool.core.io.FileUtil;
import cron.task.plugin.Task;
import net.openhft.compiler.CompilerUtils;

import java.io.*;

/**
 * java 字符串资源加载器
 *
 * @author : willian fu
 * @version : 1.0
 * @date : 2021/2/25 0025 14:50
 */
public class JavaStrTaskResourceLoader extends ClassLoader implements TaskLoader {

    private String className;

    private String javaStr;

    private Class<? extends Task> resourceClass;

    public JavaStrTaskResourceLoader(String className, String javaStr) {
        if (null == className || null == javaStr) {
            throw new RuntimeException("className and javaStr can not null");
        }
        this.className = className;
        if (javaStr.contains("package")) {
            this.javaStr = javaStr;
        } else {
            this.javaStr = "package " + className.split("\\.")[0] + ";" + javaStr;
        }
    }

    public JavaStrTaskResourceLoader(String className, File file) throws IOException {
        this(className, FileUtil.readUtf8String(file));
    }


    @Override
    public Task[] loadTaskInstance(String... clazz) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Task[] tasks = new Task[clazz.length];
        int i = 0;
        for (Class<? extends Task> task : loadClazzs(clazz)) {
            //创建任务实例对象
            tasks[i] = task.newInstance();
            i++;
        }
        return tasks;
    }

    @Override
    public Class<? extends Task>[] loadClazzs(String... clazz) throws ClassNotFoundException {
        Class<? extends Task>[] classes = new Class[clazz.length];
        int i = 0;
        for (String name : clazz) {
            this.resourceClass = CompilerUtils.CACHED_COMPILER.loadFromJava(this, className, javaStr);
            classes[i] = this.resourceClass;
            i++;
        }
        return classes;
    }
}
